package com.colorfruit.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @Description:
 * @Date: 2018/10/18
 */
public class SendWxMessageUtil {

	private static Logger logger = LoggerFactory.getLogger(SendWxMessageUtil.class);
	private static final String SEND_URL = "https://api.51xcm.cn/agent_user/agent/v1/wxSendMsg/executeWxSendModelMsg";

	public static void sendMessage(String serviceName, String toUser) {
		CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
		String respStr = null;
		StringEntity entity = null;
		JSONObject params = new JSONObject();
		JSONObject sendObject = new JSONObject();
		HttpPost httpPost = new HttpPost(SEND_URL);

		httpPost.addHeader("Content-Type", "application/json");

		sendObject.put("touser", toUser);
		sendObject.put("templatId", "-SMfHllBkem22WHGCwnc9w96sL1H1j7BEQEburXgCAY");
		sendObject.put("clickurl", "http://www.51xcm.cn/");
		sendObject.put("topcolor", "#000000");

		JSONObject first = new JSONObject();
		first.put("color", "#000000");
		first.put("value", "服务器停止服务");
		params.put("first", first);

		JSONObject keyword1 = new JSONObject();
		keyword1.put("color", "#000000");
		keyword1.put("value", "Eureka服务停止");
		params.put("keyword1", keyword1);

		JSONObject keyword2 = new JSONObject();
		keyword2.put("color", "#000000");
		keyword2.put("value", serviceName);
		params.put("keyword2", keyword2);

		JSONObject keyword3 = new JSONObject();
		keyword3.put("color", "#000000");
		keyword3.put("value", "等待开发人员检修重启");
		params.put("keyword3", keyword3);

		sendObject.put("params", params);
		entity = new StringEntity(sendObject.toString(), Charset.forName("UTF-8"));
		entity.setContentEncoding("UTF-8");
		entity.setContentType("application/json");
		httpPost.setEntity(entity);

		try {
			CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
			if (response.getStatusLine().getStatusCode() == 200) {
				respStr = EntityUtils.toString(response.getEntity());
				logger.info("微信发送消息成功消息: " + respStr);
			} else {
				logger.info("微信发送消息错误信息码: " + String.valueOf(response.getStatusLine().getStatusCode()));
				logger.info("微信发送消息错误内容: " + EntityUtils.toString(response.getEntity()));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
